package cn.stylefeng.guns.modular.business.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.config.redis.redis.util.Redishandler3;
import cn.stylefeng.guns.modular.business.common.Constants;
import cn.stylefeng.guns.modular.business.entity.BatchOrder;
import cn.stylefeng.guns.modular.business.entity.Category;
import cn.stylefeng.guns.modular.business.mapper.BatchOrderMapper;
import cn.stylefeng.guns.modular.business.model.params.BatchOrderParam;
import cn.stylefeng.guns.modular.business.model.params.BatchOrderQueryParam;
import cn.stylefeng.guns.modular.business.model.params.OrderParam;
import cn.stylefeng.guns.modular.business.model.result.BatchOrderResult;
import cn.stylefeng.guns.modular.business.service.BatchOrderService;
import cn.stylefeng.guns.modular.business.service.OrderService;
import cn.stylefeng.guns.sys.core.util.HttpUtil;
import cn.stylefeng.guns.sys.core.util.ODDGenerator;
import cn.stylefeng.guns.sys.core.util.StringUtils;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 批次订单 服务实现类
 * </p>
 *
 * @author jwj
 * @since 2019-09-09
 */
@Service
@Slf4j
public class BatchOrderServiceImpl extends ServiceImpl<BatchOrderMapper, BatchOrder> implements BatchOrderService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private Redishandler3 redishandler3;

    /**
     * rabbitmq地址
     */
    @Value("${file.rabbitBatchUrl}")
    private String rabbitBatchUrl;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(BatchOrderParam param) {
        BatchOrder entity = getEntity(param);
        JSONArray cards = JSONArray.parseArray(param.getCardNoPwd());
        entity.setSubOrderNum(cards.size());
        entity.setBatchCount(cards.size());
        entity.setSubDoingNum(entity.getSubOrderNum());
        entity.setSubAllQuota(cards.size() * entity.getBatchQuota());
        String cateStr = redishandler3.getHash(Constants.CATEGORY_SELF_HASH_KEY, "", param.getCardCataoryId().toString());
        if (StringUtils.isNotEmpty(cateStr)) {
            Category category = JSONObject.parseObject(cateStr, Category.class);
            if (category.getPid() != null) {
                String parentStr = redishandler3.getHash(Constants.CATEGORY_SELF_HASH_KEY, "", category.getPid().toString());
                if (StringUtils.isNotEmpty(parentStr)) {
                    Category parentCate = JSONObject.parseObject(parentStr, Category.class);
                    entity.setCardTypeId(parentCate.getCategoryId());
                    entity.setCardTypeName(parentCate.getName());
                }
            }
        }
        entity.setBatchNo("BT" + ODDGenerator.getD(StringUtils.replace(UUID.randomUUID().toString(), "-", "")));
        this.save(entity);
        //发送至队列
        try {
            String result = HttpUtil.sendPostJson(rabbitBatchUrl, JSONObject.toJSONString(entity), "utf-8");
            if (!"ok".equals(result)) {
                throw new ServiceException(500, "队列未找到，请通知管理员");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 新增
     *
     * @param param
     * @author jwj
     * @Date 2019-09-09
     */
    @Override
    public boolean processOrder(BatchOrderParam param) {
        JSONArray cards = JSONArray.parseArray(param.getCardNoPwd());
        UpdateWrapper<BatchOrder> updateWrapper = new UpdateWrapper<>();
        Integer sub_fail_order_num = 0;
        Integer fail_order_num = 0;
        Integer sub_doing_num = 0;
        Integer sub_success_order_num = 0;
        String reason = "";
        for (Object obj : cards) {
            JSONObject card = (JSONObject) obj;
            OrderParam orderParam = new OrderParam();
            try {
                orderParam.setOwnerUser(param.getCardOwner());
                orderParam.setOwnerUserId(param.getCardOwnerId());
                orderParam.setSubQuota(param.getBatchQuota());
                orderParam.setAmount(new BigDecimal("" + (param.getBatchQuota() * param.getPayRate())).setScale(2, BigDecimal.ROUND_HALF_UP));
                orderParam.setPayRate(param.getPayRate());
                orderParam.setCardNo(card.getString("cardNo"));
                orderParam.setCardPassword(card.getString("cardPassword"));
                orderParam.setCardCataoryId(param.getCardCataoryId());
                orderParam.setCardCataoryName(param.getCardCataoryName());
                orderParam.setCardQuotaId(param.getCardQuotaId());
                orderParam.setCardQuotaName(param.getCardQuotaName());
                orderParam.setBatchOrderId(param.getBatchId());
                ResponseData responseData = orderService.create(orderParam);
                if (responseData.getSuccess()) {
                    sub_success_order_num = sub_success_order_num + 1;
                } else {
                    log.error("批量提交订单返回处理错误：" + responseData.getMessage());
                    sub_fail_order_num = sub_fail_order_num + 1;
                    fail_order_num = fail_order_num + 1;
                    sub_doing_num = sub_doing_num + 1;
                    reason += "卡密：" + card.getString("cardPassword") + "提交失败，原因：" + responseData.getMessage() + "<br>";
                }
            } catch (Exception e) {
                log.error("批量提交有一个卡密处理错误：" + e.getMessage());
                sub_fail_order_num = sub_fail_order_num + 1;
                fail_order_num = fail_order_num + 1;
                sub_doing_num = sub_doing_num + 1;
                reason += "卡密：" + card.getString("cardPassword") + "提交失败<br>";
                e.printStackTrace();
            }
        }
        if (!sub_fail_order_num.equals(0)) {
            updateWrapper.setSql("sub_fail_order_num = sub_fail_order_num + " + sub_fail_order_num);
        }
        if (!sub_success_order_num.equals(0)) {
            updateWrapper.setSql("sub_success_order_num = sub_success_order_num + " + sub_success_order_num);
        }
        if (!fail_order_num.equals(0)) {
            updateWrapper.setSql("fail_order_num = fail_order_num + " + fail_order_num);
        }
        if (!fail_order_num.equals(0)) {
            updateWrapper.setSql("sub_doing_num = sub_doing_num -" + fail_order_num);
        }
        if (StringUtils.isNotEmpty(reason)) {
            updateWrapper.setSql("sub_fail_order_reason = '" + reason + "'");
        }
        updateWrapper.eq("batch_id", param.getBatchId());
        return this.update(updateWrapper);
    }


    @Override
    public void delete(BatchOrderParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(BatchOrderParam param) {
        BatchOrder oldEntity = getOldEntity(param);
        BatchOrder newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }


    @Override
    public BatchOrderResult findBySpec(BatchOrderParam param) {
        return null;
    }

    @Override
    public List<BatchOrderResult> findListBySpec(BatchOrderParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BatchOrderParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public Page<BatchOrderResult> getMyBatchOrders(Page page, BatchOrderQueryParam batchOrderQueryParam) {
        return baseMapper.getMyBatchOrders(page, batchOrderQueryParam);
    }

    private Serializable getKey(BatchOrderParam param) {
        return param.getBatchId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BatchOrder getOldEntity(BatchOrderParam param) {
        return this.getById(getKey(param));
    }

    private BatchOrder getEntity(BatchOrderParam param) {
        BatchOrder entity = new BatchOrder();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
